package com.web.service.handler.log;

import java.io.IOException;
import java.lang.reflect.Type;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestControllerAdvice
public class OperateLogsParamAdvice implements RequestBodyAdvice {
	
	@Autowired
	private ObjectMapper customObjectMapper;

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		IgnoreOperateParam paramIgnore = methodParameter.getMethodAnnotation(IgnoreOperateParam.class);
		IgnoreOperateLogs logsIgnore = methodParameter.getMethodAnnotation(IgnoreOperateLogs.class);
		return paramIgnore == null && logsIgnore == null;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		return inputMessage;
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		if(body != null) {
			try {
				String requestBody = customObjectMapper.writeValueAsString(body);
				RequestBodyUtil.saveRequestBody(requestBody);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
		return body;
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}
}
